/*
 * Copyright 2009 (c) Patrick Pietens
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package indigo.display 
{
	import indigo.utils.IDisposable;

	import indigo.utils.IDisposableEventDispatcher;

	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	
	use namespace indigo;
	
	/**
	 * The <code>ExtendedMovieClip</code> provides extra functionality to 
	 * the <code>MovieClip</code> by removing its children, listeners and 
	 * properties.
	 * 
	 * <p>
	 * Furthermore it extends the <code>MovieClip</code> object by adding some 
	 * small features.
	 * </p> 
	 * 
	 * @example
	 * 
	 * @playerversion Flash 9
	 * @langversion ActionScript 3.0
	 * 
	 */
	public class ExtendedMovieClip extends MovieClip implements IDisposable, IDisposableEventDispatcher
	{
		/**
		 * Boolean that indicates the <code>ExtendedMovieClip</code> is completely
		 * loaded
		 */
		private var _completed:Boolean = false;
		/**
		 * Dictionary that holds all listeners of the DisposableEventDispatcher
		 */
		private var _listeners:Array = new Array( );
		/**
		 * Boolean that indicates the ExtendedMovieClip is disposed. 
		 * Calling method and/or properties on a disposed DisplayObject will 
		 * cause runtime errors. Use this property to check if the DisplayObject
		 * is disposed.
		 */
		private var _isDisposed:Boolean = false;
		/**
		 * Boolean that indicates that the position of the 
		 * <code>ExtendedMovieClip</code> is snapped to pixels.
		 */
		private var _pixelSnapping:Boolean = false;
		/**
		 * Boolean that indicates the View is disposed when removed from stage
		 */
		public var autoDispose:Boolean = true;

		
		/**
		 * Constructor
		 * 
		 */
		public function ExtendedMovieClip()
		{
			super( );
			this.indigo::initialize( );
		}

		
		/**
		 * Executes when the <b>ExtendedMovieClip</b> is instantiated
		 * 
		 */
		indigo function initialize():void
		{			
			this.addEventListener( Event.ADDED_TO_STAGE, this.indigo::addedToStage );
			this.onInitialize( );
		}

		
		/**
		 * Executes after the <code>ExtendedMovieClip</code> is instantiated
		 * 
		 */		
		protected function onInitialize():void
		{
		}	

		
		/**
		 * Executes when the <b>ExtendedMovieClip</b> is added to Stage
		 * @param Event which triggers the method
		 * 
		 */
		indigo function addedToStage( event:Event ):void
		{
			// If the LoaderInfo is loaded
			if ( this.loaderInfo.contentType )
				this.indigo::completed( null );
                                        
			// Otherwise wait for it
			else
				this.loaderInfo.addEventListener( Event.INIT, this.indigo::completed );
			
			this.addEventListener( Event.REMOVED_FROM_STAGE, this.indigo::removedFromStage );
			this.removeEventListener( Event.ADDED_TO_STAGE, this.indigo::addedToStage );
						
			this.onAddedToStage( );			
		}

		
		/**
		 * Executes after the <code>ExtendedMovieClip</code> is added to <code>Stage</code>
		 * 
		 */		
		protected function onAddedToStage():void
		{
		}		

		
		/**
		 * Executes when the <code>ExtendMovieClip</code> is completely loaded
		 * @param Event which triggers the method
		 * 
		 */
		indigo function completed( event:Event ):void
		{
			this._completed = true;
			this.onComplete( );	
		}

		
		/**
		 * Executes after the <code>ExtendedMovieClip</code> is completely loaded
		 * 
		 */
		protected function onComplete():void
		{
		}

		
		/**
		 * The replaceChild function swaps a child for another one. 
		 * The replacement will be added at the same depth and has the same position as the original one.
		 * 
		 * @param	The placeholder which will be swapped by another DisplayObject
		 * @param	The replacement which will replace the placeholder
		 * @param	Boolean that indicates that all properties from the placeholder are copied to the replacement
		 * 
		 */
		public function replaceChild( target:DisplayObject, child:DisplayObject, duplicateProperties:Boolean = false ):DisplayObject
		{
			// Copy position of the placeholder
			child.x = target.x;
			child.y = target.y;
			
			// Copy properties
			if ( duplicateProperties )
			{
				child.filters = target.filters;
				child.transform = target.transform;
				child.cacheAsBitmap = target.cacheAsBitmap;
				child.opaqueBackground = target.opaqueBackground;
				
				if ( target.scale9Grid ) 
					child.scale9Grid = target.scale9Grid.clone( );
			}
				
			// Replace the placeholder for the replacement object	
			target.parent.addChildAt( child, target.parent.getChildIndex( target ) );
			target.parent.removeChild( target );
			
			return child;			
		}

		
		public function replaceChildAt( index:int, child:DisplayObject, duplicateProperties:Boolean = false ):DisplayObject
		{
			var myChild:DisplayObject = this.getChildAt( index );
			return this.replaceChild( myChild, child, duplicateProperties );			
		}

		
		/**
		 * Returns a Boolean that indicates a child of the ExtendedMovieClip exists and is on the DisplayList
		 * @param	DisplayObject of the ExtendedMovieClip
		 * @param	Boolean that indicates the child exists
		 * 
		 */
		public function hasChild( child:DisplayObject ):Boolean
		{
			return this.contains( child ) && child.parent == this;
		}

		
		/**
		 * Removes all children from the ExtendedMovieClip. Children are not disposed using this function. They are only removed
		 * from the displayList.
		 * 
		 */ 		
		public function removeChildren():void
		{
			var myChild:DisplayObject;
			
			var i:int = this.numChildren;
			while ( --i > -1 )
			{
				// Check if the Child is an IDisposable
				myChild = this.getChildAt( i );
				
				// Dispose children
				if ( myChild is ExtendedMovieClip && ExtendedMovieClip( myChild ).autoDispose )
					IDisposable( myChild ).dispose( );
										
				// Remove child from the displayList
				this.removeChild( myChild );
			}		
		}

		
		/**
		 * @inheritDoc
		 * 
		 */
		override public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false ):void 
		{
			this._listeners.push( new Listener( type, listener, useCapture ) );
			super.addEventListener( type, listener, useCapture, priority, useWeakReference );
		}

		
		/**
		 * @inheritDoc
		 *
		 */
		override public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void 
		{	
			super.removeEventListener( type, listener, useCapture );
			
			// Set local variables
			var myListener:Listener;
			
			// Loop through all listeners
			var i:int = this._listeners.length;
			while ( --i > -1 )
			{
				myListener = this._listeners[ i ] as Listener;
				if ( myListener.type == type && myListener.listener == listener && myListener.useCapture == useCapture )
					this._listeners.splice( i, 1 );
			}
		}

		
		/**
		 * Removes all current listeners of the EventDispatcher
		 * 
		 */
		public function removeListeners():void
		{
			var myListener:Listener;

			var i:int = this.totalListeners;
			while ( --i > -1 )
			{
				myListener = this._listeners[ i ] as Listener;
				this.removeEventListener( myListener.type, myListener.listener, myListener.useCapture );
			}
			
			this._listeners = new Array( );
		}

		
		/**
		 * Integer that indicates the total number of listeners
		 * 
		 */
		public function get totalListeners():int
		{
			return this._listeners.length;
		}

		
		/**
		 * Boolean that indicates the ExtendedMovieClip is disposed. 
		 * Calling method and/or properties on a disposed DisplayObject will 
		 * cause runtime errors. Use this property to check if the DisplayObject
		 * is disposed.
		 */
		public function get isDisposed():Boolean
		{
			return this._isDisposed;		
		}

		
		/**
		 * Number that indicates the scaling of the ExtendedMovieClip
		 * 
		 */		
		public function scale( value:Number ):void
		{
			this.scaleX = value;
			this.scaleY = value;
		}

		
		/**
		 * Boolean that indicates that the position of the 
		 * <code>ExtendedMovieClip</code> is snapped to pixels.
		 * 
		 */
		public function set pixelSnapping( value:Boolean ):void
		{
			this._pixelSnapping = value;
			
			if ( this._pixelSnapping )
			{
				this.x = this.x;
				this.y = this.y;
			}
		}

		
		/**
		 * Boolean that indicates that the position of the 
		 * <code>ExtendedMovieClip</code> is snapped to pixels.
		 * 
		 */
		public function get pixelSnapping():Boolean
		{
			return this._pixelSnapping;
		}

		
		/**
		 * @inheritDoc
		 * 
		 */
		override public function set x( value:Number ):void
		{
			super.x = this._pixelSnapping ? int( value ) : value;
		}

		
		/**
		 * @inheritDoc
		 * 
		 */
		override public function set y( value:Number ):void
		{
			super.y = this._pixelSnapping ? int( value ) : value;
		}

		
		/**
		 * Boolean that indicates the <code>ExtendedMovieClip</code> is
		 * completely loaded
		 * 
		 */
		public function get completed():Boolean
		{
			return this._completed;
		}

		
		/**
		 * Executes when the ExtendedMovieClip is removed from stage
		 * @param	Event which triggers the method
		 * 
		 */
		indigo function removedFromStage( event:Event ):void
		{
			this.addEventListener( Event.ADDED_TO_STAGE, this.indigo::addedToStage );	
			this.removeEventListener( Event.REMOVED_FROM_STAGE, this.indigo::removedFromStage );

			if ( this.autoDispose )
				this.dispose( );
				
			this.onRemovedFromStage( );
		}

		
		
		/**
		 * Executes after the <code>ExtendedMovieClip</code> is removed from <code>Stage</code>
		 * 
		 */		
		protected function onRemovedFromStage():void
		{
		}		

		
		/**
		 * Disposes the <b>ExtendedMovieClip</b> by removing and disposing all its children, clearing its graphics and removing
		 * all listeners. Disposing the <b>ExtendedMovieClip</b> will free memory and CPU resources on the next garbage collector
		 * sweep.
		 * @param	Event which triggers the method
		 * 
		 */		
		public function dispose( event:Event = null ):void
		{
			if ( !this.isDisposed )
			{
				log( "Disposing: '" + this.name + "'" );
						
				// Remove listeners
				this.removeEventListener( Event.ADDED_TO_STAGE, this.indigo::addedToStage );
				this.removeEventListener( Event.REMOVED_FROM_STAGE, this.indigo::removedFromStage );
				this.removeEventListener( Event.REMOVED_FROM_STAGE, this.dispose );

				// Remove children
				this.graphics.clear( );
				this.removeChildren( );
				this.removeListeners( );
			
				this._listeners = null;
				this._isDisposed = true;
			}
		}

		
		/**
		 * Executes after the <code>ExtendedMovieClip</code> is disposed
		 * 
		 */
		protected function onDispose():void
		{
		}
	}
}


internal class Listener
{
	public var type:String;
	public var listener:Function;
	public var useCapture:Boolean = false;

	public function Listener( type:String, listener:Function, useCapture:Boolean = false )
	{
		this.type = type;
		this.listener = listener;
		this.useCapture = useCapture;
	}
}	
